<?php

/**
 * cleanUpQcForm actions.
 *
 * @package    WacStorehouse
 * @subpackage cleanUpQcForm
 * @author     JianBinBi <prince.bi@gmail.com>
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 *
 * notes:
 * if clone as another one, below tags need to be replace to ur target module tag
 * "cleanUpQcForm" , "CleanUpQcForm", "clean_up_qc_form"
 */
class cleanUpQcFormActions extends WacCommonActions
{
    /**
     * get searching list
     * @package
     * @author     ben
     */
    public function executeGetList(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $jqGridDataHelper = JqGridDataHelper::getInstance();

        if(($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && ($request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD)!="")) || $request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
            $arrParam = array();

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParam['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
                    case "production_order_code":
                        $arrParam['orderBy'] = "wpo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "clean_up_form_code":
                        $arrParam['orderBy'] = "wcuf.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "goods_category_name":
                        $arrParam['orderBy'] = "wgc.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "status_name":
                        $arrParam['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "maker_name":
                        $arrParam['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "auditor_name":
                        $arrParam['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParam['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParam, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
    }

  /*
   * override filter list
   */
  public function filterList($listObjs)
  {
      $filterArr = array();
      if(count($listObjs) > 0)
      {
          foreach($listObjs as $listObj)
          {
              $tmpArr = $listObj->toArray();
              $tmpArr['production_order_code']        = $listObj->getWacProductionOrder()->getCode();
              $tmpArr['clean_up_form_code']           = $listObj->getWacCleanUpForm()->getCode();
              $tmpArr['goods_category_name']          = $listObj->getWacGoodsCategory()->getName();
              $tmpArr['maker_name']                   = $listObj->getWacMaker()->getUsername();

              $formatDate = new DateTime($listObj->getWacCleanUpForm()->getDeliveryDate());
              $tmpArr['clean_up_form_delivery_date']  = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getQcDate());
              $tmpArr['qc_date']                      = $formatDate->format("Y-m-d");

              $tmpArr['status_name']                  = StaticWacFormStatus::getCaptionById($listObj->getStatus());

              $filterArr[] = $tmpArr;
          }
      }

      return $filterArr;
  }

  /*
   * @return inspect result
   */
  public function inspectDataValidation(sfWebRequest $request, $params=array())
  {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();


      $exceptId = isset($reqParams['id']) ? $reqParams['id'] : 0;
      if($this->mainModuleTable->isExistedCode($reqParams['code'], $exceptId))
      {
         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
         return $result;
      }

      if(empty($reqParams['production_order_id']) || !Doctrine::getTable(WacTable::$productionOrder)->isExistedId($reqParams['production_order_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_production_order"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['clean_up_form_id']) || !Doctrine::getTable(WacTable::$cleanUpForm)->isExistedId($reqParams['clean_up_form_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_clean_up_form"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      return $result;
  }

  /*
   * @return list data array
   */
  public function executeAdd(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $objProductionOrder = Doctrine::getTable(WacTable::$productionOrder)->findOneBy('id', $reqParams['production_order_id']);
          $targetItem      = $this->mainModuleTable->create();

          if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());

            if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
            if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
            if(isset($reqParams['production_order_id'])) {$targetItem->setSrcProductionOrderId($reqParams['production_order_id']);}
            if(isset($reqParams['clean_up_form_id']))      {$targetItem->setCleanUpFormId($reqParams['clean_up_form_id']);}
            if(isset($reqParams['clean_up_form_item_id'])) {$targetItem->setCleanUpFormItemId($reqParams['clean_up_form_item_id']);}
            if(isset($reqParams['goods_category_id']))   {$targetItem->setGoodsCategoryId($reqParams['goods_category_id']);}

            $targetItem->setHoleCheck(isset($reqParams['hole_check'])?1:0);
            if(isset($reqParams['hole_check_memo']))           {$targetItem->setHoleCheckMemo($reqParams['hole_check_memo']);}
            $targetItem->setEdgeCheck(isset($reqParams['edge_check'])?1:0);
            if(isset($reqParams['edge_check_memo']))           {$targetItem->setEdgeCheckMemo($reqParams['edge_check_memo']);}
            $targetItem->setFoldCheck(isset($reqParams['fold_check'])?1:0);
            if(isset($reqParams['fold_check_memo'])) {$targetItem->setFoldCheckMemo($reqParams['fold_check_memo']);}
            $targetItem->setSpotCheck(isset($reqParams['spot_check'])?1:0);
            if(isset($reqParams['spot_check_memo'])) {$targetItem->setSpotCheckMemo($reqParams['spot_check_memo']);}
            $targetItem->setTouchCheck(isset($reqParams['touch_check'])?1:0);
            $targetItem->setLusterCheck(isset($reqParams['luster_check'])?1:0);
            $targetItem->setColorCheck(isset($reqParams['color_check'])?1:0);
            $targetItem->setClothCheck(isset($reqParams['cloth_check'])?1:0);
            
            if(isset($reqParams['standard']))                   {$targetItem->setStandard($reqParams['standard']);}
            if(isset($reqParams['level']))                      {$targetItem->setLevel($reqParams['level']);}
            if(isset($reqParams['mark']))                       {$targetItem->setMark($reqParams['mark']);}
            if(isset($reqParams['qc_date']))                    {$targetItem->setQcDate($reqParams['qc_date']);}

            if(isset($reqParams['memo']))                       {$targetItem->setMemo($reqParams['memo']);}

            $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));
            $targetItem->save();

            $this->afterAdd($request, $targetItem);

          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeEdit(sfWebRequest $request)
  {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('id'));

      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));

          if(count($reqParams)>0) {
            if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
            if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
            if(isset($reqParams['production_order_id'])) {$targetItem->setSrcProductionOrderId($reqParams['production_order_id']);}
            if(isset($reqParams['clean_up_form_id']))      {$targetItem->setCleanUpFormId($reqParams['clean_up_form_id']);}
            if(isset($reqParams['clean_up_form_item_id'])) {$targetItem->setCleanUpFormItemId($reqParams['clean_up_form_item_id']);}
            if(isset($reqParams['goods_category_id']))   {$targetItem->setGoodsCategoryId($reqParams['goods_category_id']);}

            $targetItem->setHoleCheck(isset($reqParams['hole_check'])?1:0);
            if(isset($reqParams['hole_check_memo']))           {$targetItem->setHoleCheckMemo($reqParams['hole_check_memo']);}
            $targetItem->setEdgeCheck(isset($reqParams['edge_check'])?1:0);
            if(isset($reqParams['edge_check_memo']))           {$targetItem->setEdgeCheckMemo($reqParams['edge_check_memo']);}
            $targetItem->setFoldCheck(isset($reqParams['fold_check'])?1:0);
            if(isset($reqParams['fold_check_memo'])) {$targetItem->setFoldCheckMemo($reqParams['fold_check_memo']);}
            $targetItem->setSpotCheck(isset($reqParams['spot_check'])?1:0);
            if(isset($reqParams['spot_check_memo'])) {$targetItem->setSpotCheckMemo($reqParams['spot_check_memo']);}
            $targetItem->setTouchCheck(isset($reqParams['touch_check'])?1:0);
            $targetItem->setLusterCheck(isset($reqParams['luster_check'])?1:0);
            $targetItem->setColorCheck(isset($reqParams['color_check'])?1:0);
            $targetItem->setClothCheck(isset($reqParams['cloth_check'])?1:0);

            if(isset($reqParams['standard']))                   {$targetItem->setStandard($reqParams['standard']);}
            if(isset($reqParams['level']))                      {$targetItem->setLevel($reqParams['level']);}
            if(isset($reqParams['mark']))                       {$targetItem->setMark($reqParams['mark']);}
            if(isset($reqParams['qc_date']))                    {$targetItem->setQcDate($reqParams['qc_date']);}

            if(isset($reqParams['memo']))                       {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->save();

              $this->afterEdit($request, $targetItem);
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return inspect result
   */
   protected function auditValidation(sfWebRequest $request, $objCleanUpQcForm, $params=array()) {
       $result    = JsCommonData::getSuccessDatum();
       $reqParams = $request->getParameterHolder()->getAll();

       if($objCleanUpQcForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
           $result = JsCommonData::getErrorDatum(
                   Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
           );
           return $result;
       }

       $items = $objCleanUpQcForm->getWacCleanUpQcFormItem();
       if($items->count()==0) {
           $result = JsCommonData::getErrorDatum(
                   Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_zero_item"),  WacErrorCode::$logicError
           );
           return $result;

       }

       return $result;
   }

  /*
   * @return list data array
   */
  public function executeGetFormData(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $resultSet = JsCommonData::getCommonDatum();
      $resultSet['info'] = JsCommonData::getSuccessDatum();

      $resultSet['items']['unit']           = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();

      $resultSet['items']['default']['currency_code_name'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$currency);

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
     * @return list data array
    */
    public function executeAudit(sfWebRequest $request)
    {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('clean_up_qc_form_id'));

        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = JsCommonData::getCommonDatum();

        $objCleanUpQcForm = Doctrine::getTable(WacTable::$cleanUpQcForm)->findOneBy('id', $request->getParameter('clean_up_qc_form_id'));
        if($objCleanUpQcForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init))
        {
            $resultSet['info'] = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
            );
        }

        $objCleanUpQcForm = Doctrine::getTable(WacTable::$cleanUpQcForm)->findOneBy('id', $request->getParameter('clean_up_qc_form_id'));
        $validationResult = $this->auditValidation($request, $objCleanUpQcForm);

        if($validationResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $validationResult;
        }
        else
        {
            $objFactory = $objCleanUpQcForm->getWacFactory();
            $objFactory->storeGoods($objCleanUpQcForm->getWacCleanUpQcFormItem());
            $objCleanUpQcForm->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
            $objCleanUpQcForm->setAuditorId($this->getUser()->getGuardUser()->getId());
            $objCleanUpQcForm->setAuditorDate(format_date(time()));
            $objCleanUpQcForm->save();

            $resultSet['info'] = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }


}
